import React, { FC, ReactElement, MouseEvent, useState, useRef, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { Form, Button, Toast } from '@douyinfe/semi-ui';
import { IconRefresh } from '@douyinfe/semi-icons';
import type { FormApi } from '@douyinfe/semi-ui/lib/es/form';
import {
  getFieldsGoodsList,
  getFieldsGoodsDetail,
  createOrUpdateFieldsGoodsServicesItem
} from '@/services';
import { debounce } from '@/utils/tools';
import { FieldsGoodsItem } from '../../FieldsGoods/types';

import './ItemOperate.scss';

interface IProps {
  type: 'create' | 'update';
  id?: string | number;
  initValues?: Record<string, any>;
}

const {
  Select: FormSelect,
  Input: FormInput,
  TextArea: FormTextArea,
} = Form;

const ItemOperate: FC<IProps> = (props): ReactElement => {
  const { type, id, initValues = {} } = props;

  const routeNavigate = useNavigate();

  const [goodsListLoading, setGoodsListLoading] = useState(false);
  const [goodsList, setGoodsList] = useState<FieldsGoodsItem[]>([]);
  const [submitBtnLoading, setSubmitBtnLoading] = useState(false);

  const formApiRef = useRef<FormApi<Record<string, any>>>(null);

  const handleGoodsListSearch = useCallback(async (searchValue: string) => {
    if (!formApiRef.current || !searchValue?.length) return;
    const formApi = formApiRef.current;

    // 清空值
    formApi.setValue('id', '');

    // 搜索
    setGoodsListLoading(true);
    try {
      const { code, message, data } = await getFieldsGoodsList(1, 20, searchValue);
      if (code !== 0) {
        throw new Error(message);
      }
      setGoodsList(data.list);
    } catch (e) {
      Toast.error(`请求类目列表失败：${(e as Error)?.message}`);
    }
    setGoodsListLoading(false);

  }, [formApiRef.current]);

  const handleRefreshGoods = useCallback(async (e?: MouseEvent) => {
    setGoodsListLoading(true);
    try {
      if (type === 'update' && id) {
        // 1. 先找到详情
        const { data } = await getFieldsGoodsDetail(id);
        // 2. 再搜索
        handleGoodsListSearch(data.name);
        // 3. 设置 option 的值
        formApiRef.current?.setValue?.('id', { label: data.name, value: data.id });
      } else {
        formApiRef.current?.setValue?.('id', '');
        const { code, message, data } = await getFieldsGoodsList(1, 20, '');
        if (code !== 0) {
          throw new Error(message);
        }
        setGoodsList(data.list);
      }
      Toast.success('刷新成功');
    } catch (e) {
      Toast.error(`刷新失败：${(e as Error)?.message}`);
    }
    setGoodsListLoading(false);
    e?.stopPropagation?.();
  }, [formApiRef.current, type, id]);

  const handleResetBtnClick = useCallback(() => {
    formApiRef?.current?.reset();
    handleRefreshGoods();
  }, [formApiRef.current, handleGoodsListSearch]);

  const handleSubmitBtnClick = useCallback(async () => {
    if (!formApiRef.current) return;

    setSubmitBtnLoading(true);
    try {
      const formApi = formApiRef.current;
      await formApi.validate();
      const formValues = formApi.getValues();
      const id: string = formValues?.id?.value || formValues?.id;
      const { wifi, parking } = formValues;
      const { code, message } = await createOrUpdateFieldsGoodsServicesItem({ id, wifi, parking });
      if (code !== 0) {
        throw new Error(message);
      }
      Toast.success('提交成功');
      routeNavigate('/service/fields-goods-services');
    } catch (e) {
      const errMsg = (e as Error)?.message;
      errMsg && Toast.error(`提交失败：${errMsg}`);
    }
    setSubmitBtnLoading(false);

  }, [formApiRef.current, routeNavigate]);

  useEffect(() => {
    (async () => {
      setGoodsListLoading(true);
      try {
        if (type === 'update' && id) {
          // 1. 先找到详情
          const { data } = await getFieldsGoodsDetail(id);
          // 2. 再搜索
          handleGoodsListSearch(data.name);
          // 3. 设置 option 的值
          formApiRef.current?.setValue?.('id', { label: data.name, value: data.id });
        } else {
          // 直接搜索
          const { code, message, data } = await getFieldsGoodsList(1, 20, '');
          if (code !== 0) {
            throw new Error(message);
          }
          setGoodsList(data.list);
        }
      } catch (e) {
        Toast.error(`请求类目列表失败：${(e as Error)?.message}`);
      }
      setGoodsListLoading(false);
    })();
  }, []);

  return (
    <div className="item-operate">
      <div className="item-operate-form-content">
        <Form
          layout="vertical"
          initValues={initValues}
          getFormApi={formApi => formApiRef.current = formApi}
          labelPosition="left"
          labelAlign="right"
          labelWidth="150px"
        >
          <FormSelect
            loading={goodsListLoading}
            field="id"
            label="请选择类目："
            placeholder="请选择类目(支持远程搜索)"
            filter
            remote
            showClear
            onChangeWithObject
            // searchPosition='dropdown'
            onSearch={debounce(handleGoodsListSearch, 500)}
            optionList={goodsList.map(item => ({ label: item.name, value: item.id }))}
            // onChange={v => formApiRef.current?.setValue?.('id', v)}
            style={{ overflowY: 'hidden', width: '500px' }}
            rules={[{ required: true, message: '请选择类目' }]}
            suffix={(
              <Button
                icon={<IconRefresh />}
                type="secondary"
                theme="borderless"
                onClick={debounce(handleRefreshGoods, 300)}
              />
            )}
          />
          <FormInput
            field="parking"
            label="停车场："
            placeholder="请填写停车场"
            style={{ width: '500px' }}
          />
          <FormTextArea
            field="wifi"
            label="WIFI："
            placeholder="请填写 WIFI"
            style={{ width: '500px' }}
            rows={5}
          />
          {/* {Array.from({ length: 1000 }, (item, index) => <p key={index + 1}>Paragrapth - {index + 1}</p>)} */}
        </Form>
      </div>
      <footer className="item-operate-btn-group">
        <Button onClick={handleResetBtnClick}>重置</Button>
        <Button
          loading={submitBtnLoading}
          type="primary"
          theme="solid"
          onClick={handleSubmitBtnClick}
        >
          提交
        </Button>
      </footer>
    </div>
  )
}

export default ItemOperate;
